package logic

import (
	"errors"
	Log "iot-base/auth/logger"
	"iot-base/auth/types"
	"iot-base/common/ctrltype"
	"iot-base/common/notify"
	"strconv"
	"time"
)

func CtrlResp(cmd *ctrltype.CtrlCmd) (map[string]interface{}, error) {
	Log.Log.Infof("CtrlResp cmd %v", cmd)
	var pResult *ctrltype.CtrlResult
	notify.Ctrl(cmd, 3*time.Second, func(pReply *ctrltype.CtrlResult) {
		pResult = pReply

	}, true)
	if pResult == nil {
		return nil, nil
	}
	if pResult.Error != nil && pResult.Error.Error() == "time out" {
		Log.Log.Error("CtrlResp", "cmd", cmd, "result", pResult.Error)
		return nil, errors.New("time out")
	}
	if pResult.Error != nil {
		Log.Log.Error("CtrlResp", "cmd", cmd, "result", pResult.Error)
		return nil, pResult.Error
	}
	return pResult.Result, nil
}

func GetThingRealTimeStatus(stationId string, modelId string) int {
	stationLogic := NewStationLogic()
	thingId, err := stationLogic.GetThingIdByStationIdAndModelId(stationId, modelId)
	if err != nil {
		return 0
	}
	// 查询状态.
	cmd := &ctrltype.CtrlCmd{
		ID:      types.Status,
		ThingID: thingId,
	}
	result, err := CtrlResp(cmd)
	Log.Log.Infof("[GetThingRealTimeStatus] modelId = [%v] stationId = [%v] result = [%v] err:=%v", modelId, stationId, result, err)
	if err != nil {
		return 0
	}
	if value, ok := result["msg"]; ok {
		v, _ := strconv.Atoi(value.(string))
		return v
	} else {
		return 0
	}
}
